package com.zjt.takeoutproject.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zjt.takeoutproject.common.R;
import com.zjt.takeoutproject.entity.User;
import com.zjt.takeoutproject.service.UserService;
import com.zjt.takeoutproject.utils.SMSUtils;
import com.zjt.takeoutproject.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2023-06-26
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserService userService;

//    发送手机短信验证码
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotBlank(phone)){
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码={}",code);
            //调用阿里云提供的短信服务API完成发送短信
//            SMSUtils.sendMessage("仿瑞吉外卖","SMS_461555358",phone,code);

//            //需要将生成的验证码保存到Session
//            session.setAttribute(phone,code);

            //将将生成的验证码保存到Redis中，并且设置有效期为5分钟   phone是key，code是value
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

            return R.success("手机验证码短信发送成功");
        }
        return R.error("手机验证码短信发送失败");
    }

//    客户端登录（由于前端还要传入User类不存在的code属性于是用Map接收）
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        //查看传入参数
        log.info("map:{}", map.toString());
        //获取手机号
        String phone = map.get("phone").toString();
        //获取提交验证码
        String code = map.get("code").toString();
        //获取Session里的验证码
//        Object codeInSession = session.getAttribute(phone);
        //从redis里获取验证码
        Object codeInSession = redisTemplate.opsForValue().get(phone);
        //比对验证码
        if (codeInSession != null && codeInSession.equals(code)){
            //登录成功
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(userLambdaQueryWrapper);
            //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
            if (user==null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            //登录成功，删除验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("验证码错误，登录失败");
    }
}
